package com.hongdee.base.msg.service.impl;

import com.hongdee.base.Constant;
import com.hongdee.base.msg.dao.ITBcMsgDao;
import com.hongdee.base.msg.entity.TBcMsg;
import com.hongdee.base.msg.service.ITBcMsgService;
import com.hongdee.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 名  称:TBcMsgServiceImpl
 * 类  型: class
 * 描  述: 用一句话描述类的作用
 * 路  径:com.hongdee.base.msg.service.impl
 * 作  者:术洪超
 * 日  期:2017/2/13 11:00
 */
@Service
public class TBcMsgServiceImpl implements ITBcMsgService {


    private String tabName = "T_BC_MSG";

    @Autowired
    private ITBcMsgDao iTBcMsgDao;


    /**
     * @return Map
     * @throws Exception
     * @desc 通过 JDBCDao分页查询
     * @author 术洪超
     */
    @Override
    public Map page(String companyId, String start, String limit) throws Exception {
        String sql = "select * from " + tabName;
        List param = new ArrayList();
        sql += " where company_id = ? ";
        param.add(companyId);
        return iTBcMsgDao.page(sql, param.toArray(), start, limit);
    }

    /**
     * @param id 主键 ID
     * @return ResultEntity
     * @throws Exception
     * @desc 查询详情
     * @author 术洪超
     */
    @Override
    public Map info(String id) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(id)) {
            throw new Exception("请选择短信模板");
        }
        String sql = "select * from " + tabName + " where id = ? ";
        return this.iTBcMsgDao.info(sql, new Object[]{id});
    }

    @Override
    public TBcMsg saveOrUpdate(TBcMsg data) throws Exception {

        if (null == data.getId() || StringUtils.isEmpty(data.getId())) {
            //新增时判断是否已经存在
            if (isExist(data.getMsgTypeName(), null, Constant.ADD,data.getCompanyId())) {
                throw new Exception("已存在相同的短信模板！");
            }
        } else {
            if (isExist(data.getMsgTypeName(), data.getId(), Constant.UPDATE,data.getCompanyId())) {
                throw new Exception("已存在相同的短信模板！");
            }

        }

        this.iTBcMsgDao.saveOrUpdate(data);
        return data;
    }

    @Override
    public void update(String id, String status) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择短信");
        }
        String hql = "update TBcMsg set status = :status where id = :id ";
        Map params = new HashMap();
        params.put("id", id);
        params.put("status", status);
        this.iTBcMsgDao.update(hql, params);
    }

    @Override
    public Map buildMsgContent(String companyId, String msgTypeCode, Map<Object, String> params) throws Exception {


        return null;
    }

    private boolean isExist(String msgTypeCode, String id, int type,String companyId) throws Exception {
        String sql = "select * from " + tabName + " where msg_type_code = ? and company_id=? ";
        List param = new ArrayList();
        param.add(msgTypeCode);
        param.add(companyId);
        if (Constant.UPDATE == type) {
            sql += " and  id != ? ";
            param.add(id);
        }
        Map map = this.iTBcMsgDao.page(sql, param.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }

    @Override
    public Map<String,Object> findMsgByCompanyIdAndTypeCode(String companyId,String typeCode) throws Exception {
        List<Map<String,Object>> mapList=iTBcMsgDao.list("select * from "+tabName+" where company_id=? and msg_type_name=?",companyId,typeCode);
        if(mapList!=null){
            if(mapList.size()>0){
                return mapList.get(0);
            }
        }
        return null;
    }

    /**
     * paramMap
     * key  value
     * {1}  车主名称
     * {2}  男士女士
     * {3}  车牌号
     * {4}  公里
     * {5}  时间
     * {6}  SA姓名
     * @param companyId 公司ID
     * @param typeCode 分类名称
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public boolean sendMsg(String companyId,String typeCode,String mobile,Map<String,Object> paramMap) throws Exception {
        String msg=this.getMsgContent(companyId,typeCode,paramMap);
        return false;
    }

    /**
     * 返回短信模板内容
     * @param companyId
     * @param typeCode
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public String getMsgContent(String companyId,String typeCode,Map<String,Object> paramMap) throws Exception {
        Map<String,Object> msgMap=this.findMsgByCompanyIdAndTypeCode(companyId,typeCode);
        if(msgMap==null){
            return null;
        }
        Map<String,Object> map=new HashMap<>();
        map.put("a","{1}");
        map.put("b","{2}");
        map.put("c","{3}"); // chepai
        map.put("d","{4}"); // ti 公里
        map.put("e","{5}"); //时间
        map.put("f","{6}");
        map.put("g","{7}");
        String msg=String.valueOf(msgMap.get("msgCont"));
        String plateNum = (String) paramMap.get("c"); // 获取车牌号
        for (Map.Entry<String, Object> entry: paramMap.entrySet()) {
            String key = entry.getKey();
            String keyValue = String.valueOf(map.get(key));
            String value = String.valueOf(entry.getValue());

            if(keyValue.equals("{4}")){ //如果模板内有公里数字段
                List<Map<String, Object>> list = iTBcMsgDao.list("select next_maintain_mile as nextMaintainMile from " +
                        "t_crm_car_maintain where plate_num=? order by next_maintain_mile*1 desc ",plateNum); //根据车牌信息查询公里数
                if(list.size()>0){
                    Map<String,Object> map1 = list.get(0);
                    //map1.get("next_maintain_date");
                    if(!"".equals(StringUtil.formatEmpty(map1.get("nextMaintainMile")))) {
                        String mile = (String)map1.get("nextMaintainMile"); // 获得查询结果
                        msg = msg.replace(keyValue, mile); // 将结果替换到模板
                        continue;
                    }
                }
            }
            if(keyValue.equals("{5}")){ // 注释说明同上
                List<Map<String, Object>> list = iTBcMsgDao.list("select FROM_UNIXTIME(next_maintain_time/1000,'%Y-%m-%d') nextMaintainDate " +
                        "from t_crm_car_maintain where plate_num=? order by next_maintain_time desc;",plateNum);
                if(list.size()>0){
                    Map<String,Object> map1 = list.get(0);
                    //map1.get("next_maintain_date");
                    String date = map1.get("nextMaintainDate")+"";
                    msg=msg.replace(keyValue,date);
                    continue;
                }
            }
            msg=msg.replace(keyValue,value);
        }




        return msg;
    }
}
